/**
 * @FileName: TariffService.java
 * @Author
 * @Description:
 * @Date 2016年9月21日 上午11:31:22
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.model.LocalizedConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.bean.OrgNode;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Tariff;
import cn.hpclub.server.model.TariffClass;
import cn.hpclub.server.util.InterfaceUtil;

public class TariffService{
    private static final Logger  log           = LoggerFactory.getLogger(TariffService.class);
    public static TariffService  service       = new TariffService();

    public static final String[] headesExport  = { "业务名称", "业务代码", "业务类型", "所属大类", "发布人", "发布人机构", "开始时间", "结束时间", "排序",
            "是否启用" };
    public static final String[] columnsExport = { "name", "code", "type", "tariff_class_name", "creatorName",
            "creatorOrgName", "start_date", "end_date", "sort", "enabled" };

    /**
     * @Title: getSqlSelect
     * @Description:TODO
     * @return String
     */

    public String getSqlSelect(){
        String select = "SELECT tariff.id, tariff.name, ( CASE type WHEN 0 THEN '主资费' WHEN 1 THEN '附加资费' WHEN 2 THEN '营销活动' WHEN 3 THEN '营销活动（短信）' END ) AS type, code, start_date, end_date, tariff.sort, tariff.enabled, group_concat(DISTINCT tariff_class. NAME) AS tariff_class_name, ( SELECT DisplayName FROM organization org WHERE tariff.org_id = org.id ) AS creatorOrgName, ( SELECT sys_user.user_name FROM sys_user WHERE tariff.create_by = sys_user.id ) AS creatorName, " +
                "(SELECT GROUP_CONCAT(org.DisplayName) FROM localized_config lc LEFT JOIN organization org ON org.id=lc.localized_city_id WHERE lc.business="+ LocalizedConfig.BUSINESS_TARIFF+" AND lc.business_id=tariff.id) AS localized_cities ";
        return select;
    }

    /**
     * @Title: getSqlSelect
     * @Description:导出
     * @return String
     */

    public List<Record> export(ConcurrentHashMap<String, String> searchInfo, String sqlOrgFilter){
        String select = "SELECT tariff.id, tariff.name, ( CASE type WHEN 0 THEN '主资费' WHEN 1 THEN '附加资费' WHEN 2 THEN '营销活动' WHEN 3 THEN '营销活动（短信）' END ) AS type, code, date_format(start_date,'%Y-%m-%d') as start_date, date_format(end_date,'%Y-%m-%d') as end_date, tariff.sort, if(tariff.enabled=1,'是','否') as enabled, group_concat(DISTINCT tariff_class. NAME) AS tariff_class_name, ( SELECT DisplayName FROM organization org WHERE tariff.org_id = org.id ) AS creatorOrgName, ( SELECT sys_user.user_name FROM sys_user WHERE tariff.create_by = sys_user.id ) AS creatorName ";
        List<Record> list = Db.find(select + getSqlFilter(searchInfo, sqlOrgFilter));
        return list;
    }

    /**
     * @Title: getSqlFilter
     * @Description:TODO
     * @param searchInfo
     * @param sqlOrgFilter
     * @return String
     */

    public String getSqlFilter(ConcurrentHashMap<String, String> searchInfo, String sqlOrgFilter){
        String sqlExceptSelect = "FROM tariff LEFT JOIN tariff_class_relation ON tariff_class_relation.tariff_id = tariff.id LEFT JOIN tariff_class ON tariff_class_relation.tariff_class_id = tariff_class.id WHERE tariff.is_deleted = 0 AND tariff.org_id in "
                + sqlOrgFilter;
        sqlExceptSelect += getSqlExceptSelect(searchInfo);
        return sqlExceptSelect;
    }

    /**
     * 获取查询语句
     */
    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = "";
        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " GROUP BY tariff.id ORDER BY tariff.last_updated_time DESC";

        return sqlExceptSelect;
    }

    private String buildQuery(Entry<String, String> item){
        if(item.getKey().equals("tariff_type")){
            return " AND tariff.type=" + item.getValue();
        } else if(item.getKey().equals("tariff_class")){
            return " AND tariff.id IN (SELECT tariff_id FROM tariff_class_relation WHERE tariff_class_id = '"
                    + item.getValue() + "') ";
        } else if(item.getKey().equals("selected_city")){
            return " AND tariff.org_id IN "
                    + InterfaceUtil.getChlidOrgIdSql(Integer.parseInt(item.getValue()), Constant.MAX_ORG_LEVEL, true);
        } else if(item.getKey().equals("tariff_name")){
            return " AND tariff.name LIKE '%" + item.getValue() + "%'";
        } else if(item.getKey().equals("tariff_code")){
            return " AND tariff.code LIKE '%" + item.getValue() + "%'";
        } else if(item.getKey().equals("is_enabled")){
            return " AND tariff.enabled = " + item.getValue() + " ";
        } else{
            return "";
        }
    }

    public List<Entry<String, String>> getTariffClassList(){
        List<Entry<String, String>> list = new ArrayList<Entry<String, String>>();
        List<Record> recordList = Db.find("SELECT id, name FROM tariff_class WHERE is_deleted=0 ORDER BY sort ASC");
        for(Record record : recordList){
            list.add(new SimpleEntry<String, String>(record.getStr("name"), String.valueOf(record.getInt("id"))));
        }
        return list;
    }

    /**
     * @Title: getOrgMaps
     * @Description:获取市级分公司构集合
     * @return Map<String,Integer>
     */
    public List<Entry<String, String>> getCityLevelOrgList(){
        List<Entry<String, String>> list = new ArrayList<Entry<String, String>>();

        OrgNode root = InterfaceUtil.getOrgTree(InterfaceUtil.getIdTop(), 1, false);
        if(root == null || root.getSubNode() == null || root.getSubNode().size() == 0){
            return list;
        }
        /* 大掌柜根节点，显示所有地市分公司 */
        int accountOrgId = InterfaceUtil.getOrgId();
        if(accountOrgId == root.getId()){
            for(OrgNode node : root.getSubNode()){
                list.add(new SimpleEntry<String, String>(node.getDisplayName(), String.valueOf(node.getId())));
            }
        } else{
            for(OrgNode node : root.getSubNode()){
                if(accountOrgId == node.getId()){
                    list.add(new SimpleEntry<String, String>(node.getDisplayName(), String.valueOf(node.getId())));
                }
            }
        }
        return list;
    }

    public boolean getTariffByCityAndCode(int city_org_id, String code, int tariffId){
        StringBuffer sql = new StringBuffer("SELECT * FROM tariff WHERE code=? AND is_deleted=0 ");
        if(tariffId > 0){
            sql.append(" AND id !=" + tariffId);
        }
        sql.append(" AND  org_id = ").append(city_org_id).append(" ");
        List<Record> tariffList = Db.find(sql.toString(), code);
        return tariffList.size() > 0 ? true : false;
    }

    public List<Record> getTariffByCityAndCodeForDeleted(int city_org_id, String code){
        StringBuffer sql = new StringBuffer("SELECT * FROM tariff WHERE code=? AND is_deleted=1 ");

        sql.append(" AND  org_id = ").append(city_org_id).append(" ");
        List<Record> tariffList = Db.find(sql.toString(), code);
        return tariffList;
    }

    /**
     * @Title: getTariffByTariffClass
     * @Description:根据大类获取小类数据，业务权限配置（资费类）和泛店员业务权限配置共用
     * @param tariffClassList
     * @return JSONArray
     */
    public JSONArray getTariffByTariffClass(List<Record> tariffClassList){
        JSONArray busDatas = new JSONArray();
        JSONObject tariff = null;
        for(Record r : tariffClassList){
            List<Record> tariffList = Tariff.dao.getTariffByTariffClassId(r.getInt(TariffClass.ID));

            tariff = new JSONObject();
            tariff.put(TariffClass.ID, r.getInt(TariffClass.ID));
            tariff.put(TariffClass.NAME, r.getStr(TariffClass.NAME));

            if(null != tariffList && tariffList.size() > 0){
                tariff.put("children", JsonKit.toJson(tariffList));
                busDatas.add(tariff);
            } else{
                // 过滤掉没有小类的大类数据，因为没有小类就无法办理业务，配置了无意义
                continue;
            }

        }

        return busDatas;
    }

}
